package de.dhbw_stuttgart.wi2011i.outofapples.persistence;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import de.dhbw_stuttgart.wi2011i.outofapples.logging.Logger;

public abstract class EinkaufsblockBase implements Einkaufsblock {
	private final List<WeakReference<ChangeCallback>> _changeCallbacks = new ArrayList<WeakReference<ChangeCallback>>();
	
	protected final Logger logger;
	
	protected EinkaufsblockBase(Logger logger) {
		this.logger = logger;
	}

	public void registerChangeCallback(ChangeCallback callback) {
		this._changeCallbacks.add(new WeakReference<ChangeCallback>(callback));
	}
	public void unregisterChangeCallback(ChangeCallback callback) {
		this._changeCallbacks.remove(callback);
	}
	
	protected void triggerBlockChange() {
		this.logger.info("BlockChange triggered by %s", this.getClass().getName());
		
		ArrayList<WeakReference<ChangeCallback>> references = new ArrayList<WeakReference<ChangeCallback>>(_changeCallbacks);
		for (WeakReference<ChangeCallback> reference : references) {
			ChangeCallback callback = reference.get();
			if (callback != null) 
				callback.blockChangeOccured();
		}
	}
	protected void triggerListChange(UUID id) {
		this.logger.info("ListChange triggered by %s for %s", this.getClass().getName(), id);
		
		ArrayList<WeakReference<ChangeCallback>> references = new ArrayList<WeakReference<ChangeCallback>>(_changeCallbacks);
		for (WeakReference<ChangeCallback> reference : references) {
			ChangeCallback callback = reference.get();
			if (callback != null) 
				callback.listChangeOccured(id);
		}
	}
	protected void triggerItemChange(UUID id) {
		this.logger.info("ItemChange triggered by %s for %s", this.getClass().getName(), id);
		
		ArrayList<WeakReference<ChangeCallback>> references = new ArrayList<WeakReference<ChangeCallback>>(_changeCallbacks);
		for (WeakReference<ChangeCallback> reference : references) {
			ChangeCallback callback = reference.get();
			if (callback != null) 
				callback.itemChangeOccured(id);
		}
	}
}
